/*
 *  Copyright 2011.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.pc.ui.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 *
 */
public class FileIO {

    /**
     *  Store properties in file, with specific comments. If file
     * not exist, created his parent dir and new file.
     * 
     * @param file File where properties will be stored
     * @param properties Specific propperties
     * @param comments Comments to comment
     * @throws IOException if writing this property list to the
     *          specified output stream throws an IOException.
     */
    public static void store(File file, Properties properties, String comments)
            throws IOException {

        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }

        properties.store(new BufferedWriter(new FileWriter(file)), comments);
    }

    /**
     *  Load properties from file, if properties is null
     * created new instance
     *
     * @param file File where from properties will be loaded
     * @param properties Specific propperties
     * @return propperties
     * @throws IOException if writing this property list to the
     *          specified output stream throws an IOException.
     */
    public static Properties load(File file, Properties properties)
            throws IOException {

        if (properties == null) {
            properties = new Properties();
        }

        properties.load(new BufferedInputStream(new FileInputStream(file)));

        return properties;
    }

    /**
     *  Write data to file, if file not exist - it will created. If file
     * dir not exist - it will be created including any necessary.
     *
     * @param data file content
     * @param file File data properties will be stored
     * @throws IOException if writing this property list to the
     *          specified output stream throws an IOException.
     */
    public static void write(String data, File file) throws IOException {
        file.getParentFile().mkdirs();
        BufferedWriter buff = new BufferedWriter(new FileWriter(file));
        buff.write(data);
        buff.close();
    }
}
